import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon } from 'antd'
import _ from 'lodash'
import moment from 'moment';

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete, getYear, getPayCycleDom } from 'lib/fun'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const { RangePicker } = DatePicker;
const Option = Select.Option;
const OptGroup = Select.OptGroup;
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

class Filter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      selectedCategory: ['all'],
      selectedProject: [],
      projectCate: [],
      projectList: [],
      dateFormat: 'YYYY-MM-DD'
    }
    this.defaultTime = [moment(moment().year()+'-01-01'), moment()];
  }

  componentDidMount(){
    // this.loadArea();
    if(this.props.common.user&&this.props.common.user.user&&this.state.treeData.length == 0){
      this.setState({
        treeData:[{
          areaId: this.props.common.user.user.areaId,
          areaName: this.props.common.user.user.areaName,
        }]
      });
    }
    this.loadProjectCategory();
    this.loadProject();
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.common.user&&nextProps.common.user.user&&this.state.treeData.length == 0){
      this.setState({
        treeData:[{
          areaId: nextProps.common.user.user.areaId,
          areaName: nextProps.common.user.user.areaName,
        }]
      });
    }
  }

  loadProjectCategory = ()=>{
    var self = this;
    Ajax({
      url: '/projectCate/list',
      success: function(data){
        var projectCate = []
        const loop = (data) => {
          data.forEach((item) => {
            const { projectCategoryId, projectCategoryCode, projectCategoryName } = item;
            projectCate.push({
              projectCategoryId, 
              projectCategoryCode, 
              projectCategoryName
            });
            if(item.children&&item.children.length > 0){
              loop(item.children);
            }
          });
        };
        loop(data);
        
        self.setState({
          projectCate: projectCate
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadProject = ()=>{
    var self = this;
    Ajax({
      url: '/project/list',
      data: {
        currentPage: 1,
        perPage: 1000
      },
      success: function(data){
        self.setState({
          projectList: data.list
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadArea = (treeNode)=>{
    console.log('load area');
    var self = this;
    var selected = findRowData(self.state.treeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              treeData = data.list;
            }
            self.setState({
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  handleSearch = (e) => {
    var self = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      const { areaIds, projectIds, projectCategoryIds, birthday, states } = values;
      var backObj = {
        dateBegin: birthday[0].format('YYYY-MM-DD'),
        dateEnd: birthday[1].format('YYYY-MM-DD'),
        projectCategoryIds: projectCategoryIds&&projectCategoryIds.length > 0&&projectCategoryIds[0] == 'all'?undefined:projectCategoryIds,
        projectIds: projectIds&&projectIds.length > 0?projectIds:undefined,
        areaIds: areaIds?[areaIds]:undefined,
        states: states&&states.length > 0&&states[0] == 'all'?undefined:states
      }
      self.props.handleFilter(backObj);
    });
  }

  changeCategory = (value)=>{
    this.setState({
      selectedCategory: value
    });

    this.props.form.setFieldsValue({
      projectId: []
    });
    console.log(value);
  }

  handleReset = () => {
    this.props.form.resetFields();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const formItemLayout2 = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);
    const years = getYear();

    const { payCycleCode } = this.props.config;
    const projectRegisterEn = this.props.common.projectRegisterEn||[];

    var userType = this.props.common&&this.props.common.user&&this.props.common.user.user&&this.props.common.user.user.userType == 'common';

    let projectListDom = null;
    if(userType){
      projectListDom = this.state.projectList.map((item)=>{
        return <Option key={item.projectId}>{ item.projectName }</Option>
      })
    }else if(this.state.selectedCategory.length > 0){
      var type = []
      if(this.state.selectedCategory[0] == 'all'){
        _.each(this.state.projectCate, (cc)=>{
          type.push(cc.projectCategoryId);
        });
      }else{
        type = this.state.selectedCategory
      }
      // console.log(type);
      projectListDom = type.map((item)=>{
        var proList = _.filter(this.state.projectList, function(o) { return o.projectCategoryId == item });
        var find = _.find(this.state.projectCate, (obj)=>{ return obj.projectCategoryId == item });
        return <OptGroup key={ find.projectCategoryId } label={ find.projectCategoryName }>
                {
                  proList.map((pro)=>{
                    return <Option key={pro.projectId}>{ pro.projectName }</Option>
                  })
                }
              </OptGroup>
      })
    }
    return (<Form
          horizontal
          className="ant-advanced-search-form"
          onSubmit={this.handleSearch}
        >
          <Row gutter={20}>
            <Col span={6}>
              <FormItem {...formItemLayout} label="补贴登记区划">
                {getFieldDecorator("areaIds", {
                  initialValue: this.state.treeData.length>0?this.state.treeData[0].areaId+"":""
                })(
                    this.props.treeData?<Select
                      size="default"
                    >
                      {
                        (this.props.treeData||[]).map(function(obj){
                          return (<Option key={obj.areaId+""} value={ obj.areaId+"" }>{ obj.areaName }</Option>)
                        })
                      }
                    </Select>:<TreeSelect
                      size="default"
                      loadData={ this.loadArea }
                    >
                      { treeNodes }
                    </TreeSelect>
                )}
              </FormItem>
            </Col>
            {userType?"":<Col span={9}>
              <FormItem {...formItemLayout2} label="项目分类">
                {getFieldDecorator("projectCategoryIds", {
                  initialValue: ['all']
                })(
                  <TreeSelect
                    treeDefaultExpandAll
                    multiple
                    treeCheckable
                    size="default"
                    showCheckedStrategy={SHOW_PARENT}
                    onChange={this.changeCategory}
                  >
                    <SelectTreeNode value="all" title="全部分类" key="all">
                      {
                        (this.state.projectCate||[]).map(function(obj){
                          return (<SelectTreeNode key={obj.projectCategoryCode} value={ obj.projectCategoryId+"" } title={ obj.projectCategoryName }></SelectTreeNode>)
                        })
                      }
                    </SelectTreeNode>
                  </TreeSelect>
                )}
              </FormItem>
            </Col>
            }
            <Col span={9}>
              <FormItem {...formItemLayout2} label="补贴项目">
                {getFieldDecorator("projectIds")(
                  <Select
                    multiple
                    size="default"
                  >
                  {
                    projectListDom
                  }
                  </Select>
                )}
              </FormItem>       
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="状态">
                {getFieldDecorator("states", {
                  initialValue: ['all']
                })(
                  <TreeSelect
                    treeDefaultExpandAll
                    multiple
                    treeCheckable
                    size="default"
                    showCheckedStrategy={SHOW_PARENT}
                  >
                    <SelectTreeNode value="all" title="全部状态" key="all">
                      {
                        (projectRegisterEn||[]).map(function(obj){
                          return (<SelectTreeNode key={obj.code} value={ obj.code+"" } title={ obj.mean }></SelectTreeNode>)
                        })
                      }
                    </SelectTreeNode>
                  </TreeSelect>
                )}
              </FormItem>
            </Col>
            <Col span={9}>
              <FormItem {...formItemLayout2} label="时间区间">
                {getFieldDecorator("birthday", {
                  initialValue: this.defaultTime
                })(
                  <RangePicker 
                    allowClear={false}
                    format={this.state.dateFormat} 
                  />
                )}
              </FormItem>
            </Col>
            <Col>
              <div className="btn-box">
                <Button type="primary" htmlType="submit">查询</Button>
              </div>
            </Col>
          </Row>
        </Form>);
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

module.exports = connect(mapStateToProps)(Form.create()(Filter))